<template>
  <div class="box">
    <el-card>
      <el-form class="searchForm" :inline="true" :model="queryForm" label-width="90px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="创建时间">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="queryForm.time"
                unlink-panels
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 250px; background-color: transparent"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="项目名称">
              <el-input v-model="queryForm.name" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务标题">
              <el-input v-model="queryForm.keytask" placeholder="请输入任务标题" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工作举措">
              <el-input v-model="queryForm.tasknote" placeholder="请输入工作举措" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="完成标准">
              <el-input v-model="queryForm.standstr" placeholder="请输入完成标准" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标志性成果">
              <el-input v-model="queryForm.objectivearr" placeholder="请输入标志性成果" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" @click="pageChange(1)">查询</el-button>
              <el-button v-if="edit" type="primary" @click="onAdd">添加</el-button>
              <el-button v-if="edit" type="primary" @click="onFile">导入</el-button>
              <el-button v-if="edit" type="primary" @click="onCancel">取消提交</el-button>
              <el-button type="primary" @click="onApprovalRecord">审批记录</el-button>
              <el-button v-if="edit" type="primary" @click="onAddTask">添加任务</el-button>
              <!-- <el-button type="primary" @click="onTaskledger">任务台账</el-button> -->
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table
        v-loading="loading"
        ref="mTable"
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        border
        :height="tableHeight"
        highlight-current-row
        @current-change="handleCurrentChange"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
      >
        <el-table-column v-if="edit" fixed="left" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              @click="onDel(scope.row)"
              type="text"
              size="small"
              :disabled="scope.row.valid == '1' || scope.row.valid == '4' ? false : true"
              >删除</el-button
            >
            <el-button
              @click="onRevise(scope.row)"
              type="text"
              size="small"
              :disabled="scope.row.valid == '1' || scope.row.valid == '4' ? false : true"
              >修改</el-button
            >
            <el-button
              v-show="scope.row.proid == 0"
              @click="onSubmit(scope.row)"
              type="text"
              size="small"
              :disabled="scope.row.valid == '1' || scope.row.valid == '4' ? false : true"
              >提交</el-button
            >
          </template>
        </el-table-column>
        <el-table-column type="index" width="80" label="序号" align="center">
          <template slot-scope="scope">
            {{ scope.row.indexNumber }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="项目名称/任务标题" min-width="300">
          <template slot-scope="scope">
            <span :style="{ paddingLeft: (scope.row.level || 0) * 20 + 'px' }"> </span>
            <el-tooltip
              effect="dark"
              :content="scope.row.proid == 0 ? scope.row.name : scope.row.keytask"
              placement="right"
            >
              <el-link v-if="scope.row.proid == 0" type="success" @click="onlinktitle(scope.row)">
                <i class="el-icon-folder-opened" style="color: #409eff"></i>
                {{ scope.row.name }}
              </el-link>
              <el-link v-else style="margin-left: 2rem" type="success" @click="onlinkTaskTitle(scope.row)">
                <i class="el-icon-document" style="color: #67c23a"></i>
                {{ scope.row.keytask || scope.row.name }}
              </el-link>
            </el-tooltip>
            <!-- <span v-if="scope.row.keytask" class="key-task-tag">重点</span> -->
          </template>
        </el-table-column>
        <el-table-column prop="newfill" label="最新进展" min-width="180" align="center"> </el-table-column>
        <el-table-column prop="comper" label="平均完成率" min-width="180">
          <template slot-scope="scope">
            <el-progress class="showProgressColor" :percentage="scope.row.comper || 0"></el-progress>
          </template>
        </el-table-column>
        <el-table-column prop="tasknote" label="工作举措" min-width="200" align="center">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.tasknote" effect="dark" :content="scope.row.tasknote" placement="top">
              <span class="task-note">{{ scope.row.tasknote | ellipsis }}</span>
            </el-tooltip>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="standstr" label="完成标准" min-width="200" align="center">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.standstr" effect="dark" :content="scope.row.standstr" placement="top">
              <span class="task-note">{{ scope.row.standstr | ellipsis }}</span>
            </el-tooltip>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="objectivearr" label="预期标志性结果" min-width="200" align="center">
          <template slot-scope="scope">
            <el-tooltip v-if="scope.row.objectivearr" effect="dark" :content="scope.row.objectivearr" placement="top">
              <span class="task-note">{{ scope.row.objectivearr | ellipsis }}</span>
            </el-tooltip>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" min-width="120" align="center"> </el-table-column>

        <el-table-column prop="mdates" label="创建时间" min-width="120" align="center"> </el-table-column>
        <el-table-column prop="username" label="创建人" min-width="120" align="center"> </el-table-column>
        <el-table-column prop="validstr" label="状态" min-width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.validstr)" size="small">
              {{ scope.row.validstr }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin: 10px"
        :current-page="queryForm.pagenum"
        :page-sizes="[20, 50, 100]"
        :page-size="queryForm.pagesize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="sizeChange"
        @current-change="pageChange"
      />
    </el-card>

    <el-dialog :title="title" :visible.sync="Visible" width="600px">
      <el-form :model="form" :rules="formRules" ref="formRef">
        <el-form-item label="项目名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="来源" :label-width="formLabelWidth" prop="source">
          <el-input v-model="form.source" clearable placeholder="请输入来源"></el-input>
          <!-- <el-select v-model="form.source" clearable placeholder="请选择来源">
            <el-option v-for="item in Source" :key="item.id" :label="item.keyinfo" :value="item.valueinfo"></el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="承办部门" :label-width="formLabelWidth" prop="hostdpid">
          <el-input disabled placeholder="请选择部门" v-model="form.hostdpname" autocomplete="off">
            <el-button slot="prepend" icon="el-icon-plus" @click="Clickcurr()"></el-button>
            <el-button
              slot="append"
              icon="el-icon-close"
              @click="
                form.hostdpid = ''
                form.hostdpname = ''
              "
            ></el-button>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Visible = false">取消</el-button>
        <el-button type="primary" @click="CreateTask('Save')">保存</el-button>
        <el-button type="primary" @click="CreateTask('Task')">创建并添加任务</el-button>
      </div>
    </el-dialog>
    <renyuanbm :visiblesbm="visiblesbm" @fatherbm="visiblesbm = false" @onChoosebm="onChoosebm"></renyuanbm>
  </div>
</template>

<script>
import renyuanbm from '@/views/jichuxinxi/zuzhirenyuan/renyuandalog/renyuanbm.vue'
import {
  Dictionary,
  LocalDate,
  QueryPageTree,
  Save,
  Del as ProjectDel,
  QueryInfoByID,
  isCreatePro
} from '@/api/Project/index'
import { Del as taskDel } from '@/api/task/index'
import { GetCheckInfo } from '@/api/Approval/index'

export default {
  name: 'ProjectEstablishment',
  data() {
    return {
      title: '',
      tableHeight: '',
      file: '',
      queryForm: {
        pagenum: 1,
        pagesize: 20
      },
      Source: [],
      total: 0,
      tableData: [],
      loading: false,
      Visible: false,
      formRules: {
        name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        source: [{ required: true, message: '请输入来源', trigger: 'change' }],
        hostdpid: [{ required: true, message: '请选择承办部门', trigger: 'change' }]
      },
      form: {},
      time: '',
      formLabelWidth: '120px',
      handleCurrent: null,
      visiblesbm: false,
      edit: false,
      debounceonSearch: this.$debounce(this.onSearch, 200)
    }
  },
  components: { renyuanbm },

  filters: {
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 30) {
        return value.slice(0, 30) + '...'
      }
      return value
    }
  },

  watch: {
    '$store.getters.approveIClose': {
      immediate: true,
      handler(newId) {
        this.debounceonSearch()
      }
    },
    $route: {
      immediate: true,
      handler(newId) {
        if (newId.path == '/Fourth/ProjectEstablishment/ProjectEstablishment') {
          this.debounceonSearch()
        }
      }
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 350
    this.onIsCreatePro()
    this.onSource()
    this.debounceonSearch()
  },

  methods: {
    // 获取进度条状态
    getProgressStatus(percentage) {
      if (percentage >= 100) return 'success'
      if (percentage >= 80) return 'warning'
      return 'exception'
    },

    // 获取状态标签类型
    getStatusType(status) {
      const statusMap = {
        草拟: 'info',
        审批中: 'warning',
        已通过: 'success',
        退回: 'danger',
        已完成: 'success'
      }
      return statusMap[status] || 'info'
    },

    async onIsCreatePro() {
      this.loading = true
      const result = await isCreatePro({ userid: this.$store.getters.userInfo.id })
      this.edit = result.success
      // this.edit = true
      this.loading = false
      // this.edit = true
    },

    onChoosebm(row) {
      this.form.hostdpname = row.orgname
      this.form.hostdpid = row.id
      this.$refs.formRef && this.$refs.formRef.validateField('hostdpid')
    },

    Clickcurr() {
      this.visiblesbm = true
    },

    handleCurrentChange(val) {
      this.handleCurrent = val
    },

    sizeChange(size) {
      this.queryForm.pagesize = size
      this.debounceonSearch()
    },

    pageChange(page) {
      this.queryForm.pagenum = page
      this.debounceonSearch()
    },

    async onSource() {
      this.loading = true
      const { content } = await Dictionary({ groupinfo: 'TaskSource' })
      this.Source = content
      const res = await LocalDate()
      this.time = res.content
      this.loading = false
    },

    async onSearch() {
      this.loading = true
      if (this.queryForm.time != undefined) {
        this.queryForm.mdates1 = this.queryForm.time[0]
        this.queryForm.mdates2 = this.queryForm.time[1]
      } else {
        this.queryForm.mdates1 = this.queryForm.time
        this.queryForm.mdates2 = this.queryForm.time
      }

      this.queryForm.loguserid = this.$store.getters.userInfo.id
      this.queryForm.logusername = this.$store.getters.userInfo.username
      this.queryForm.logdpid = this.$store.getters.userInfo.orgid
      this.queryForm.logdpname = this.$store.getters.userInfo.orgname

      const { content } = await QueryPageTree(this.queryForm)
      this.tableData = this.$handleTree(content.list, 'id', 'proid', 'children')
      this.calculateIndexNumbers(this.tableData)
      console.log('树形结构数据:', this.tableData)
      this.total = content.total
      this.$nextTick(() => {
        this.$refs.mTable.doLayout()
      })
      this.loading = false
    },

    onAdd() {
      this.title = '督办项目新增'
      this.form = {
        hostdpname: this.$store.getters.userInfo.orgname,
        hostdpid: this.$store.getters.userInfo.orgid
      }
      this.Visible = true
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate()
      })
    },

    async CreateTask(type) {
      try {
        await this.$refs.formRef.validate()

        if (this.form.id == undefined) {
          this.form.id = 0
          this.form.mdate = this.time
          this.form.userid = this.$store.getters.userInfo.id
          this.form.username = this.$store.getters.userInfo.username
          this.form.dpid = this.$store.getters.userInfo.orgid
          this.form.dpname = this.$store.getters.userInfo.orgname
        }

        const res = await Save(this.form)
        if (res.success) {
          this.$message.success(res.message)
          this.Visible = false
          if (type === 'Task') {
            this.$router.push('/Fourth/Tasklist/TasklistAdd?id=' + res.docid + '&state=A&source=' + this.form.source)
          }
          this.debounceonSearch()
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        this.$message.error('请完善表单信息')
      }
    },

    async onRevise(row) {
      if (row.proid == 0) {
        const { content } = await QueryInfoByID({ id: row.id })
        this.title = '督办项目修改'
        this.form = content
        this.Visible = true
      } else {
        this.$router.push('/Fourth/Tasklist/TasklistAdd?id=' + row.id + '&state=U')
      }
    },

    onFile() {
      this.$router.push('/Fourth/ProjectEstablishment/ImportDetails')
    },

    onDel(row) {
      this.$confirm('此操作将永久删除该项目及其所有子项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          if (row.proid == 0) {
            await ProjectDel({ id: row.id })
          } else {
            await taskDel({ id: row.id })
          }
          this.$message.success('删除成功!')
          this.debounceonSearch()
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },

    onSubmit(row) {
      if (!row) {
        this.$message.error('请选择一条数据')
        return
      }

      this.$confirm('确定全部任务已经创建完毕?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await this.$ApproveInsert({
            visible: true,
            title: row.name,
            documentid: row.id,
            historyid: 0,
            modelcode: 'DBProject'
          })
        })
        .catch(() => {
          this.$message.info('已取消提交')
        })
    },

    onAddTask() {
      if (this.handleCurrent && this.handleCurrent.proid == 0) {
        this.$router.push('/Fourth/Tasklist/TasklistAdd?id=' + this.handleCurrent.id + '&state=A')
      } else {
        this.$message.error('请选择一条项目数据')
      }
    },

    onTaskledger() {
      if (this.handleCurrent && this.handleCurrent.proid == 0) {
        this.$router.push(
          '/Fourth/Tasklist/ImportDetailsC?id=' + this.handleCurrent.id + '&title=' + this.handleCurrent.name
        )
      } else {
        this.$message.error('请选择一条项目数据')
      }
    },

    async onCancel() {
      if (this.handleCurrent && this.handleCurrent.proid == 0) {
        this.$confirm('确定要取消提交?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            await this.$ApproveCancel({
              modelCode: 'DBProject',
              documentID: this.handleCurrent.id,
              userName: this.$store.getters.userInfo.username
            })
            this.debounceonSearch()
          })
          .catch(error => {
            if (error === 'cancel') {
              this.$message.info('已取消')
            }
          })
      } else {
        this.$message.error('请选择一条项目数据')
      }
    },

    onApprovalRecord() {
      if (this.handleCurrent && this.handleCurrent.proid == 0) {
        this.$Approve({ visible: true, documentid: this.handleCurrent.id, modelcode: 'DBProject' })
      } else {
        this.$message.error('请选择一条项目数据')
      }
    },
    calculateIndexNumbers(treeData, parentIndex = '') {
      treeData.forEach((node, index) => {
        if (parentIndex == '') {
          // 根节点：直接使用序号
          node.indexNumber = `${index + 1}`
        } else {
          // 子节点：父序号-子序号
          node.indexNumber = `${parentIndex}-${index + 1}`
        }

        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          this.calculateIndexNumbers(node.children, node.indexNumber)
        }
      })
    },
    onlinktitle(row) {
      this.$router.push('/Fourth/Tasklist/ImportDetailsC?id=' + row.id + '&title=' + row.name)
    },
    onlinkTaskTitle(row) {
      this.$router.push('/Fourth/Tasklist/TasklistAddC?id=' + row.id + '&title=' + row.keytask + '&proid=' + row.proid)
    }
  }
}
</script>

<style scoped>
.box {
  padding: 20px;
  background-color: #fdfbf2;
}
.el-card {
  background-color: transparent;
}
.box >>> .el-table,
.el-table__expanded-cell {
  background-color: #fcfaee;
  /* border: 1px solid #000; */
}

.box >>> input {
  background-color: transparent;
}
.box >>> .el-select {
  width: 100%;
}
.box >>> .el-table th {
  background-color: #fcfaee !important;
  /* border: 1px solid #000; */
}
.box >>> .el-table tr {
  background-color: #fcfaee !important;
  /* border: 1px solid #000; */
}

.title {
  height: 30px;
  line-height: 30px;
  background: rgba(0, 0, 0, 0.3);
  font-size: 14px;
  text-transform: uppercase;
  margin: 0 0 5px;
  padding: 0 10px;
  display: inline-block;
  letter-spacing: 0.5px;
}
.showProgressColor >>> .el-progress-bar__inner {
  background: linear-gradient(to right, blue, pink);
}

.box >>> .el-link {
  border-bottom: 1px solid #13ce66;
}
.box >>> .el-link span {
  overflow: hidden; /* 隐藏溢出的内容 */
  white-space: wrap; /* 防止文本换行 */
  display: inline-block; /* 设置为行内块元素 */
}
.showProgressColor >>> .el-progress-bar__inner {
  background: linear-gradient(to right, blue, pink);
}

.key-task-tag {
  display: inline-block;
  background: #ff4d4f;
  color: white;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
  font-weight: bold;
}

.task-note {
  cursor: pointer;
  color: #666;
  font-size: 12px;
}

/* 树形表格样式优化 */
.box >>> .el-table .el-table__row {
  transition: background-color 0.3s;
}

.box >>> .el-table .el-table__row:hover {
  background-color: #f5f7fa !important;
}

/* 层级缩进样式 */
.box >>> .el-table .tree-indent {
  display: inline-block;
  vertical-align: middle;
}
</style>
